﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

using ApocDev.TownsApi;

using Image = System.Drawing.Image;
using Path = System.IO.Path;

namespace TownsModder
{
    /// <summary>
    /// Interaction logic for GraphicsEditorWindow.xaml
    /// </summary>
    public partial class GraphicsEditorWindow : Window
    {
        public GraphicsEditorWindow()
        {
            InitializeComponent();
            lstGraphics.ItemsSource = ModFiles.Graphics.Objects.Values;
            lstGraphics.SelectedItem = ModFiles.Graphics.Objects["citsleeping"];
        }

        void SetGraphicsImage(Image img)
        {
            if (Dispatcher.Thread != Thread.CurrentThread)
            {
                Dispatcher.Invoke(new Action<Image>(SetGraphicsImage), img);
                return;
            }

            BitmapImage bi = new BitmapImage();
            bi.BeginInit();
            var ms = new MemoryStream();
            img.Save(ms, ImageFormat.Png);
            ms.Seek(0, SeekOrigin.Begin);
            bi.StreamSource = ms;
            bi.EndInit();

            imgTile.Source = bi;
        }

        private Thread _animationThread;
        private void lstGraphics_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var graphicsObj = lstGraphics.SelectedItem as GraphicsIni.GraphicsObject;

            Image img = graphicsObj.GetImage();
            if (_animationThread != null)
                _animationThread.Abort();
            _animationThread = null;
            if (graphicsObj.AnimationTiles != "0" && !string.IsNullOrWhiteSpace(graphicsObj.AnimationTiles))
            {
                _animationThread = new Thread(g =>
                    {
                        int numFrames = int.Parse((g as GraphicsIni.GraphicsObject).AnimationTiles);
                        int curFrame = 0;
                        while (true)
                        {
                            SetGraphicsImage((g as GraphicsIni.GraphicsObject).GetImage(curFrame++ % numFrames));

                            Thread.Sleep(250);
                        }
                    });
                _animationThread.IsBackground = true;
                _animationThread.Start(graphicsObj);
            }

            SetGraphicsImage(img);
            wgInfo.SelectedObject = graphicsObj;
            wgInfo.HelpVisible = false;
            wgInfo.ToolbarVisible = false;

        }
    }
}
